package com.student.manage.controller;


import com.student.manage.annotation.RepeatSubmit;
import com.student.manage.aop.RepeatSubmitAspect;
import com.student.manage.entity.LoginToken;
import com.student.manage.entity.model.LoginResult;
import com.student.manage.entity.model.RegisterResult;
import com.student.manage.entity.model.UserTokenInfo;
import com.student.manage.entity.vo.UserLoginVo;
import com.student.manage.entity.vo.UserRegisterVo;
import com.student.manage.service.IUserService;
import com.student.manage.util.CaptchaUtils;
import com.student.manage.util.DigestUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Controller
@Slf4j
public class IndexController {


    @Resource
    private IUserService userService;

    @GetMapping(value = {"", "/"})
    public String IndexController() {
        return "redirect:/user/list";
    }

    @GetMapping(value = {"/error.html"})
    public String error() {
        return "error";
    }


    @RequestMapping(value = {"/login.html"})
    public String login(@RequestParam(value = "not_login", required = false) String not_login, Model model, HttpSession session) {
        if (not_login != null) {
            model.addAttribute("not_login", true);
        }

        log.info("login.html,{}", session.getId());
        session.setAttribute(RepeatSubmitAspect.REPEAT_SUBMIT, DigestUtils.md5(LocalDateTime.now().toString()));
        return "login";
    }


    @PostMapping(value = {"/login"})
    @RepeatSubmit(fallback = "redirect:/login.html")
    public String login(UserLoginVo userLoginVo,
                        Model model,
                        HttpServletRequest request,
                        HttpSession session,
                        HttpServletResponse response,
                        @CookieValue(value = LoginToken.TOKEN_HEADER, required = false) String token) {

        log.info("{}", session.getId());

        log.info("{}", token);


        LoginResult loginResult = userService.login(userLoginVo);

        if (loginResult.isSuccess()) {

            Cookie cookie = new Cookie(LoginToken.TOKEN_HEADER, loginResult.getLoginToken().getToken());
            cookie.setMaxAge((int) LoginToken.DEFAULT_EXPIRE_TIME.toSeconds());
            response.addCookie(cookie);

            return "redirect:/";
        }
        request.setAttribute("login_result", loginResult);
        return "forward:/login.html";
    }


    @RequestMapping(value = {"/register.html"})
    public String register(Model model, @SessionAttribute(required = false, value = "register_result") RegisterResult registerResult, HttpSession session) {

        log.info("register,{}", registerResult);
        session.setAttribute(RepeatSubmitAspect.REPEAT_SUBMIT, DigestUtils.md5(LocalDateTime.now().toString()));
        return "register";
    }

    /**
     * 用户注册
     *
     * @param session
     * @return
     */

    @PostMapping(value = {"/register"})
    @RepeatSubmit(fallback = "redirect:/register.html")
    public String register(Model model, HttpSession session, UserRegisterVo user) {

        RegisterResult registerResult = userService.register(user);


        if (registerResult.isSuccess()) {
            session.setAttribute("register_result", registerResult);

            return "redirect:/register_success";
        } else {
            model.addAttribute("register_result", registerResult);
            return "forward:/register.html";
        }


    }

    @GetMapping(value = {"/register_success"})
    public String registerResult(@SessionAttribute(required = false, value = "register_result") RegisterResult registerResult, HttpSession session, Model model) {

        if (registerResult == null) {
            return "redirect:/register.html";
        }


        session.removeAttribute("register_result");

        model.addAttribute("register_result", registerResult);

        return "register_success";

    }

    // 生成验证码
    @GetMapping(value = {"/captcha"})
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String code = CaptchaUtils.getCaptcha(request, response);
        log.info("{}", code);


    }


    @GetMapping(value = {"/logout"})
    public String logout(HttpServletResponse response, @RequestAttribute(value = UserTokenInfo.TOKEN_INFO_KEY) UserTokenInfo userTokenInfo, HttpSession session) {

        Cookie cookie = new Cookie(LoginToken.TOKEN_HEADER, null);

        cookie.setMaxAge(0);

        response.addCookie(cookie);

        return "redirect:/login.html";

    }

}
